package mysql

import (
	"errors"
	"gorm.io/gorm"
)

// TODO: 用户表
type User struct {
	gorm.Model
	Username  string `gorm:"type:varchar(100);not null;unique"`
	Password  string `gorm:"type:char(64);not null"`
	Email     string `gorm:"type:varchar(100);null"`
	AvatarUrl string `gorm:"type:varchar(100);"`
	Mobile    string `gorm:"type:char(11);unique;not null"`
	NickName  string `gorm:"type:varchar(100);not null"`
}

// TODO：实名
type UserIdentity struct {
	gorm.Model
	UserId       uint
	User         User   `gorm:"ForeignKey:UserId"`
	IdentityCard string `gorm:"type:char(18);not null"`
	RealName     string `gorm:"type:varchar(30);not null"`
}

// 创建用户
func CreateUser(User User) User {
	db.Create(&User)
	return User
}

func CreateUserIdentity(UserIdentity UserIdentity) UserIdentity {
	db.Create(&UserIdentity)
	return UserIdentity
}

func GetUserIdentity(UserId int64) UserIdentity {
	UserIdentity := UserIdentity{}
	db.Where("user_id = ?", UserId).First(&UserIdentity)
	return UserIdentity
}

func GetUserName() {

}

// 手机号登录
func MobileLogin(user User) User {
	db.Where("mobile = ?", user.Mobile).First(&user)
	return user
}

// 查找手机号
func SearchMobile(user User) User {
	db.Where("mobile =?", user.Mobile).First(&user)
	return user
}

// 用户名密码登录
func UserLogin(user User) (User, error) {
	username := user.Username
	password := user.Password
	db.Table("users").Where("username = ?", username).First(&user)
	if user.ID == 0 {
		return User{}, errors.New("用户名错误")
	}

	if user.Password != password {
		return User{}, errors.New("密码错误")
	}
	return user, nil
}

// 修改头像
func UserModifyAvatar(user User) User {
	db.Model(&user).Update("avatar_url", user.AvatarUrl)
	return user
}
